<script lang="ts" setup>
import { getRuleListAPI } from '@/apis/car';
import type {  CarListParams, Rule } from '@/types/car';
import { ref } from 'vue';
import { utils, writeFileXLSX } from 'xlsx';

const ruleList = ref<Rule[]>([])
const params = ref<CarListParams>({
  page: 1,
  pageSize: 5
})
const total = ref(0)
// const dialogVisible = ref(false)

// 获取规则列表
const getRuleList = async () => {
  try {
    const res = await getRuleListAPI(params.value)
    ruleList.value = res.data.rows
    total.value = res.data.total
  } catch {
    
  }
}
getRuleList()

const chargeTypeMap = new Map<Rule['chargeType'], string>([
  ['duration', '时长收费'],
  ['turn','按次收费'],
  ['partition', '分段收费'],
])

const exportToExcel = () => {
  // 1.创建工作簿
  const workbook = utils.book_new()
  // 2.创建工作表
  const workSheet = utils.json_to_sheet(
    ruleList.value.map((item, index) => ({
      ...item,
      id: index + 1,
      chargeType:chargeTypeMap.get(item.chargeType)
    }))
  )
  // 3.把工作表添加到工作簿中
  utils.book_append_sheet(workbook, workSheet, '计费规则')
  // 4.改写表头
  utils.sheet_add_aoa(workSheet,
    [
    ['序号', '计费规则编号', '计费规则名称', '免费时长(分钟)', '收费上限(元)', '计费方式', '计费规则']
  ],
    { origin: 'A1' })
  // 5.导入下载xlxs文件
  writeFileXLSX(workbook,'计费规则表.xlsx')
}

</script>

<template>
  <div class="rule-container">
    <div class="create-container">
      <el-button type="primary">增加停车计费规则</el-button>
      <el-button @click="exportToExcel()">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table :data="ruleList" style="width: 100%">
        <el-table-column align="center" type="index" label="序号" width="100" />
        <el-table-column align="center" label="计费规则编号" prop="ruleNumber" />
        <el-table-column align="center" label="计费规则名称" prop="ruleName" />
        <el-table-column align="center" label="免费时长(分钟)" prop="freeDuration" />
        <el-table-column align="center" label="收费上限(元)" prop="chargeCeiling" />
        <el-table-column align="center" label="计费方式">
          <template #default="scope">
            {{ chargeTypeMap.get(scope.row.chargeType) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="计费规则" prop="ruleNameView" />
        <el-table-column align="center" label="操作" fixed="right" width="200">
          <template #default>
            <el-button size="small" type="text">编辑</el-button>
            <el-button size="small" type="text">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<style scoped>
.el-button{
  margin-left: 20px;
  margin-top: 20px;
}
.table{
  margin-top: 20px;
}
</style>